//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.weilai.controller;

import com.github.pagehelper.PageInfo;
import com.weilai.controller.exceptionHandler.BusinessException;
import com.weilai.controller.exceptionHandler.Code;
import com.weilai.controller.exceptionHandler.SystemException;
import com.weilai.domain.*;
import com.weilai.service.*;


import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;

import com.weilai.util.UploadUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;


import javax.servlet.http.HttpServletRequest;


@Controller
@Api(tags = "帖子相关操作", description = "对帖子进行相关操作的接口")
public class PostsController {
    // 创建日志对象
    private static final Logger log = LoggerFactory.getLogger(PostsController.class);
    @Autowired
    private PostsService postsService;
    @Autowired
    private UserService userService;
    @Autowired
    private VideosService videosService;
    @Autowired
    private ThoughtService thoughtService;
    @Autowired
    private FollowersService followersService;
    @Autowired
    private CommentsService commentsService;

    // 添加帖子
    @ApiOperation(value = "添加帖子的方法")
    @PostMapping("/posts/add")
    public ModelAndView add(@RequestParam String title,
                            @RequestParam String content,
                            @RequestParam MultipartFile image,
                            @RequestParam String categoryName,
                            HttpServletRequest request) throws IOException {
        try {
            // 参数校验
            if (title == null || title.trim().isEmpty()) {
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "标题不能为空");
            }
            if (content == null || content.trim().isEmpty()) {
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "内容不能为空");
            }

            Posts posts = new Posts();
            posts.setTitle(title);
            posts.setContent(content);
            posts.setType("文章");
            posts.setCategoryName(categoryName);

            // 分类校验
            Integer categoryId = postsService.selectCategorieById(categoryName);
            if (categoryId == null) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "分类不存在");
            }
            posts.setCategoryId(categoryId);

            // 用户校验
            Object userIdObj = request.getSession().getAttribute("userId");
            if (userIdObj == null) {
                throw new BusinessException(Code.PROJECT_ACCESS_DENIED, "用户未登录");
            }
            int userId = (int) userIdObj;
            posts.setUserId(userId);

            // 图片处理
            if (!image.isEmpty()) {
                long maxImageSize = 2 * 1024 * 1024;
                if (image.getSize() > maxImageSize) {
                    throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "图片大小不能超过2MB");
                }
                String fileName = UploadUtil.upload(image);
                posts.setImageUrl(fileName);
            }

            postsService.add(posts);
            return new ModelAndView("postArticle").addObject("result", "添加成功");
        } catch (BusinessException e) {
            throw e;
        } catch (IOException e) {
            throw new SystemException(Code.SYSTEM_IO_ERROR, "文件上传失败", e);
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "添加帖子失败", e);
        }
    }

    // 删除帖子
    @ApiOperation(value = "删除帖子的方法")
    @PostMapping("/posts/delete")
    @ResponseBody
    public Map<String, Object> deleteById(@RequestParam int id, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 权限校验
            Object userIdObj = request.getSession().getAttribute("userId");
            if (userIdObj == null) {
                throw new BusinessException(Code.PROJECT_ACCESS_DENIED, "用户未登录");
            }
            int userId = (int) userIdObj;

            // 检查帖子是否存在且属于当前用户
            Posts post = postsService.selectById(id);
            if (post == null) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "帖子不存在");
            }
            if (post.getUserId() != userId) {
                throw new BusinessException(Code.PROJECT_ACCESS_DENIED, "无权删除他人帖子");
            }

            postsService.deleteById(id);
            result.put("message", "删除成功");
        } catch (BusinessException e) {
            result.put("message", e.getMessage());
        } catch (Exception e) {
            result.put("message", "删除帖子失败");
        }
        return result;
    }

    // 回显数据以便修改帖子
    @ApiOperation(value = "回显数据的方法")
    @GetMapping("/updatePosts")
    public ModelAndView updatePosts(@RequestParam int id, HttpServletRequest request) {
        try {
            // 权限校验
            Object userIdObj = request.getSession().getAttribute("userId");
            if (userIdObj == null) {
                throw new BusinessException(Code.PROJECT_ACCESS_DENIED, "用户未登录");
            }
            int userId = (int) userIdObj;

            Posts posts = postsService.selectById(id);
            if (posts == null) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "帖子不存在");
            }
            if (posts.getUserId() != userId) {
                throw new BusinessException(Code.PROJECT_ACCESS_DENIED, "无权查看他人帖子");
            }

            return new ModelAndView("editArticle").addObject("posts", posts);
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "获取帖子数据失败", e);
        }
    }

    // 修改帖子
    @ApiOperation(value = "修改帖子的方法")
    @PostMapping("/postsUpdate")
    public ModelAndView update(@RequestParam int id,
                               @RequestParam String title,
                               @RequestParam String content,
                               @RequestParam MultipartFile image,
                               @RequestParam String categoryName,
                               HttpServletRequest request) throws IOException {
        try {
            // 参数校验
            if (title == null || title.trim().isEmpty()) {
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "标题不能为空");
            }

            // 权限校验
            Object userIdObj = request.getSession().getAttribute("userId");
            if (userIdObj == null) {
                throw new BusinessException(Code.PROJECT_ACCESS_DENIED, "用户未登录");
            }
            int userId = (int) userIdObj;

            Posts existingPost = postsService.selectById(id);
            if (existingPost == null) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "帖子不存在");
            }
            if (existingPost.getUserId() != userId) {
                throw new BusinessException(Code.PROJECT_ACCESS_DENIED, "无权修改他人帖子");
            }

            Posts posts = new Posts();
            posts.setId(id);
            posts.setTitle(title);
            posts.setContent(content);
            posts.setCategoryName(categoryName);
            Integer categoryId = postsService.selectCategorieById(categoryName);
            if (categoryId == null) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "分类不存在");
            }
            posts.setCategoryId(categoryId);

            if (!image.isEmpty()) {
                long maxImageSize = 2 * 1024 * 1024;
                if (image.getSize() > maxImageSize) {
                    throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "图片大小不能超过2MB");
                }
                String fileName = UploadUtil.upload(image);
                posts.setImageUrl(fileName);
            }

            postsService.update(posts);
            return new ModelAndView("personCenterArticle").addObject("result", "更新成功");
        } catch (BusinessException e) {
            throw e;
        } catch (IOException e) {
            throw new SystemException(Code.SYSTEM_IO_ERROR, "文件上传失败", e);
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "更新帖子失败", e);
        }
    }


    // 在首页查询所有帖子
    @ApiOperation(value = "首页初始帖子加载（前10条）")
    @GetMapping("/mainPageRecommend")
    public ModelAndView loadInitialPosts(HttpServletRequest request,
                                         @RequestParam(defaultValue = "1") int pageNum,
                                         @RequestParam(defaultValue = "10") int pageSize) {
        try {
            // 获取帖子分页数据
            PageInfo<Posts> postsPageInfo = postsService.selectAll(pageNum, pageSize);
            if (postsPageInfo == null || postsPageInfo.getList().isEmpty()) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "暂无数据");
            }
            // 获取帖子对应的用户信息
            List<User> postsUsers = new ArrayList<>();
            for (Posts post : postsPageInfo.getList()) {
                User user = userService.getUserById(post.getUserId());
                user.setEmail("***");
                user.setPassword("***");
                postsUsers.add(user);
            }
            // 判断用户角色，决定返回的视图
            User user = (User) request.getSession().getAttribute("user");
            String viewName = "mainPageRecommend";
            if (user != null && "admin".equals(user.getRole())) {
                viewName += "Manager";
            }
            // 遍历帖子列表，判断每个帖子用户是否点赞
            if (user!= null) {
                for (Posts post : postsPageInfo.getList()) {
                    int isLiked = postsService.isLike(post.getId(), user.getId());
                    post.setIsLiked(isLiked);
                }
            }

            return new ModelAndView(viewName)
                    .addObject("postsPageInfo", postsPageInfo)
                    .addObject("postsUsers", postsUsers);
        } catch (BusinessException e) {
            throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND,"业务异常");
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "查询列表失败",e);
        }
    }

    @ApiOperation(value = "分页加载更多帖子")
    @GetMapping("/mainPageRecommend/more")
    public ResponseEntity<Map<String, Object>> loadMorePosts(
            HttpServletRequest request,
            @RequestParam(defaultValue = "2") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize
    ) {

        try {
            // 获取帖子分页数据
            PageInfo<Posts> postsPageInfo = postsService.selectAll(pageNum, pageSize);
            if (postsPageInfo == null || postsPageInfo.getList().isEmpty()) {
                return ResponseEntity.ok(Collections.singletonMap("message", "暂无数据"));
            }

            // 获取帖子对应的用户信息，添加空值检查
            List<User> postsUsers = new ArrayList<>();
            for (Posts post : postsPageInfo.getList()) {
                User user = userService.getUserById(post.getUserId());
                user.setEmail("***");
                user.setPassword("***");
                if (user != null) {
                    postsUsers.add(user);
                } else {
                    return ResponseEntity.ok(Collections.singletonMap("message", "未查询到用户"));
                }
            }

            // 判断用户角色
            User user = (User) request.getSession().getAttribute("user");
            // 判断每个帖子用户是否点赞
            if (user != null) {
                for (Posts post : postsPageInfo.getList()) {
                    int isLiked = postsService.isLike(post.getId(), user.getId());
                    post.setIsLiked(isLiked);
                }
            }

            // 构建返回数据
            Map<String, Object> response = new HashMap<>();
            response.put("postsPageInfo", postsPageInfo);
            response.put("postsUsers", postsUsers);

            return ResponseEntity.ok(response);
        } catch (BusinessException e) {
            // 记录日志
            e.printStackTrace();
            // 根据业务异常返回合适的HTTP状态码，比如400表示请求有误
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Collections.singletonMap("error", e.getMessage()));
        } catch (Exception e) {
            // 记录日志
            e.printStackTrace();
            // 对于其他异常返回500表示服务器内部错误
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Collections.singletonMap("error", "查询列表失败"));
        }
    }

    // 查询别人所有文章
    @ApiOperation(value = "查询别人所有文章的方法")
    @GetMapping("/posts/selectAllArticle")
    public ModelAndView selectAllArticle(@RequestParam int userId, HttpServletRequest request) {
        try {
            List<Posts> posts = postsService.selectAllArticle(userId);
            if (posts == null || posts.isEmpty()) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "该用户暂无文章");
            }

            User author = userService.getUserById(userId);
            author.setEmail("***");
            author.setPassword("***");
            if (author == null) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "用户不存在");
            }


            return new ModelAndView("allUsersArticle")
                    .addObject("user", author)
                    .addObject("posts", posts);
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "查询用户文章失败", e);
        }
    }

    // 查询自己所有文章
    @ApiOperation(value = "查询自己所有文章的方法")
    @GetMapping("/posts/selectMyAllArticle")
    public ModelAndView selectMyAllArticle(HttpServletRequest request) {
        try {
            Object userIdObj = request.getSession().getAttribute("userId");
            if (userIdObj == null) {
                throw new BusinessException(Code.PROJECT_ACCESS_DENIED, "用户未登录");
            }
            int userId = (int) userIdObj;

            List<Posts> posts = postsService.selectMyAllArticle(userId);
            if (posts == null || posts.isEmpty()) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "您还没有发表过文章");
            }

            User user = userService.getUserById(userId);
            user.setEmail("***");
            user.setPassword("***");
            return new ModelAndView("personCenterArticle")
                    .addObject("user", user)
                    .addObject("posts", posts);
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "查询我的文章失败", e);
        }
    }

    //查询别人所有讨论
    @ApiOperation(value = "查询所有讨论的方法")
    @GetMapping("/posts/selectAllDiscussion")
    public ModelAndView selectAllDiscussion(@RequestParam int userId, HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();
        try {
            List<Posts> posts = postsService.selectAllDiscussion(userId);
            List<User> user = new ArrayList<>();
            for (Posts post : posts) {
                User users = userService.getUserById(post.getUserId());
                users.setEmail("***");
                users.setPassword("***");
                user.add(users);
            }
            mav.addObject("user", user);
            mav.addObject("posts", posts);
            mav.setViewName("allUsersDiscussion");
            return mav;
        } catch (Exception e) {
            // 捕获异常并抛出 BusinessException
            throw new BusinessException(Code.SYSTEM_UNKNOWN_ERROR, "查询别人所有讨论时发生未知错误");
        }
    }

    //查询自己所有讨论
    @ApiOperation(value = "查询自己所有讨论的方法")
    @GetMapping("/posts/selectMyAllDiscussion")
    public ModelAndView selectMyAllDiscussion(HttpServletRequest request) {
        int userId = (int)request.getSession().getAttribute("userId");
        ModelAndView mav = new ModelAndView();
        try {
            List<Posts> posts = postsService.selectMyAllDiscussion(userId);
            List<User> user = new ArrayList<>();
            for (Posts post : posts) {
                User users = userService.getUserById(post.getUserId());
                users.setEmail("***");
                users.setPassword("***");
                user.add(users);
            }
            mav.addObject("user", user);
            mav.addObject("posts", posts);
            mav.setViewName("allMyDiscussion");
            return mav;
        } catch (Exception e) {
            // 捕获异常并抛出 BusinessException
            throw new BusinessException(Code.SYSTEM_UNKNOWN_ERROR, "查询自己所有讨论时发生未知错误");
        }
    }

    // 根据标题关键字查询帖子
    @ApiOperation(value = "根据标题关键字查询帖子的方法")
    @GetMapping("/posts/select/title")
    public ModelAndView selectByTitle(@RequestParam String title, HttpServletRequest request) {
        try {
            if (title == null || title.trim().isEmpty()) {
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "搜索关键词不能为空");
            }

            List<Posts> posts = postsService.selectByTitle(title);
            if (posts == null || posts.isEmpty()) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "未找到相关帖子");
            }

            List<User> users = new ArrayList<>();
            for (Posts post : posts) {
                User user = userService.getUserById(post.getUserId());
                user.setEmail("***");
                user.setPassword("***");
                if (user == null) {
                    throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "用户信息缺失");
                }
                users.add(user);
            }

            return new ModelAndView("titlePosts")
                    .addObject("user", users)
                    .addObject("posts", posts);
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "搜索帖子失败", e);
        }
    }

    // 根据时间范围查询帖子
    @ApiOperation(value = "根据时间范围查询帖子的方法")
    @GetMapping("/posts/select/date")
    public ModelAndView selectByDate(@RequestParam String date1, @RequestParam String date2, HttpServletRequest request) {
        try {
            // 日期格式校验
            String format = "yyyy-MM-dd";
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern(format);
            LocalDate.parse(date1, dtf);
            LocalDate.parse(date2, dtf);

            List<Posts> posts = postsService.selectByDate(date1, date2);
            if (posts == null || posts.isEmpty()) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "该时间段内没有帖子");
            }

            List<User> users = new ArrayList<>();
            for (Posts post : posts) {
                User user = userService.getUserById(post.getUserId());
                user.setEmail("***");
                user.setPassword("***");
                if (user == null) {
                    throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "用户信息缺失");
                }
                users.add(user);
            }

            return new ModelAndView("datePosts")
                    .addObject("user", users)
                    .addObject("posts", posts);
        } catch (DateTimeParseException e) {
            throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "日期格式错误，请使用yyyy-MM-dd格式");
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "按时间查询帖子失败", e);
        }
    }

    //根据id查询帖子
    @ApiOperation(value="根据id查询帖子的方法")
    @GetMapping("/posts/select/id")
    public ModelAndView selectById(@RequestParam int id, HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();

        // 参数校验
        if (id <= 0) {
            throw new BusinessException(
                    Code.PROJECT_VALIDATE_ERROR,
                    "帖子ID必须为正整数"
            );
        }

        try {
            // 查询帖子
            Posts posts = postsService.selectById(id);
            if (posts == null) {
                throw new BusinessException(
                        Code.PROJECT_DATA_NOT_FOUND,
                        "帖子不存在"
                );
            }

            // 查询用户信息
            User user = userService.getUserById(posts.getUserId());

            if (user == null) {
                throw new BusinessException(
                        Code.PROJECT_DATA_NOT_FOUND,
                        "用户不存在"
                );
            }
            user.setEmail("***");
            user.setPassword("***");
            // 查询用户相关数据
            List<Posts> p = postsService.selectByUserId(posts.getUserId());
            List<Thought> t = thoughtService.selectAllUsersThought(posts.getUserId());
            List<User> f = followersService.selectFansById(posts.getUserId());

            User user1 =(User) request.getSession().getAttribute("user");
            boolean isLiked = false;
            boolean isFollowing = false;
            if(user1 != null) {
                //判断是否点赞
                isLiked = postsService.isLikedByUser(user1.getId(),id);
                //判断是否关注
                isFollowing = followersService.isFollowing(user1.getId(), posts.getUserId());
            }

            // 设置视图数据

            mav.addObject("user", user);
            mav.addObject("posts", posts);
            mav.addObject("postsNum", p != null ? p.size() : 0);
            mav.addObject("thoughtNum", t != null ? t.size() : 0);
            mav.addObject("fansNum", f != null ? f.size() : 0);
            mav.addObject("isLiked", isLiked); // 添加点赞状态到视图
            mav.addObject("isFollowing",isFollowing);//添加关注状态到视图
            mav.setViewName("articleDetail");

        } catch (BusinessException e) {
            // 业务异常直接抛出
            throw e;
        } catch (Exception e) {
            // 系统异常包装后抛出
            throw new SystemException(
                    Code.SYSTEM_DB_ERROR,
                    "查询帖子详情失败",
                    e
            );
        }

        return mav;
    }

    //根据id查询帖子
    @ApiOperation(value="根据id查询帖子的方法")
    @GetMapping("/posts/selectMe/id")
    public ModelAndView selectMeById(@RequestParam int id, HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();

        // 参数校验
        if (id <= 0) {
            throw new BusinessException(
                    Code.PROJECT_VALIDATE_ERROR,
                    "帖子ID必须为正整数"
            );
        }

        try {
            // 查询帖子
            Posts posts = postsService.selectById(id);
            if (posts == null) {
                throw new BusinessException(
                        Code.PROJECT_DATA_NOT_FOUND,
                        "帖子不存在"
                );
            }

            // 查询用户相关数据
            List<Posts> p = postsService.selectByUserId(posts.getUserId());
            List<Thought> t = thoughtService.selectAllUsersThought(posts.getUserId());
            List<User> f = followersService.selectFansById(posts.getUserId());

            User user =(User) request.getSession().getAttribute("user");
            boolean isLiked = false;
            boolean isFollowing = false;
            if(user != null) {
                //判断是否点赞
                isLiked = postsService.isLikedByUser(user.getId(),id);
                //判断是否关注
                isFollowing = followersService.isFollowing(user.getId(), posts.getUserId());
            }

            // 设置视图数据

            mav.addObject("user", user);
            mav.addObject("posts", posts);
            mav.addObject("postsNum", p != null ? p.size() : 0);
            mav.addObject("thoughtNum", t != null ? t.size() : 0);
            mav.addObject("fansNum", f != null ? f.size() : 0);
            mav.addObject("isLiked", isLiked); // 添加点赞状态到视图
            mav.addObject("isFollowing",isFollowing);//添加关注状态到视图
            mav.setViewName("authorArticleDetail");

        } catch (BusinessException e) {
            // 业务异常直接抛出
            throw e;
        } catch (Exception e) {
            // 系统异常包装后抛出
            throw new SystemException(
                    Code.SYSTEM_DB_ERROR,
                    "查询帖子详情失败",
                    e
            );
        }

        return mav;
    }

    // 点赞
    @ApiOperation(value = "点赞的方法")
    @PostMapping("/posts/like")
    @ResponseBody
    public Map<String,Object> like(@RequestParam int postId, HttpServletRequest request) {
        try {
            Object userIdObj = request.getSession().getAttribute("userId");
            int userId = (int) userIdObj;

            Posts post = postsService.selectById(postId);
            if (post == null) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "帖子不存在");
            }

            return postsService.like(userId,postId);
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "点赞操作失败", e);
        }
    }

    //取消点赞
    @ApiOperation(value = "取消点赞的方法")
    @PostMapping("/posts/cancelLike")
    @ResponseBody
    public Map<String,Object> cancelLike(@RequestParam int postId, HttpServletRequest request) {
        try {
            Object userIdObj = request.getSession().getAttribute("userId");
            if (userIdObj == null) {
                throw new BusinessException(Code.PROJECT_ACCESS_DENIED, "用户未登录");
            }
            int userId = (int) userIdObj;

            Posts post = postsService.selectById(postId);
            if (post == null) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "帖子不存在");
            }
            return postsService.cancelLike(userId,postId);
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "取消点赞失败", e);
        }
    }



    @ApiOperation(value = "获取指定帖子所有评论的方法（分页）")
    @GetMapping("/postsComments")
    public ResponseEntity<?> getPostsComments(
            @RequestParam int postId,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "5") int pageSize,
            HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 校验帖子是否存在
            Posts post = postsService.selectById(postId);
            if (post == null) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "帖子不存在");
            }

            // 获取分页评论数据
            PageInfo<Comments> commentsPageInfo = commentsService.getCommentsByPostIdWithPaging(postId, pageNum, pageSize);
            List<Comments> comments = commentsPageInfo.getList();

            // 处理无评论情况
            if (pageNum == 1 && (comments == null || comments.isEmpty())) {
                response.put("info","暂无评论");
            }

            // 逐个获取评论用户信息（也有批量方式，效率高速度快难度大）
            List<User> commentUsers = new ArrayList<>();
            for (Comments comment : comments) {
                User user = userService.getUserById(comment.getUserId());
                if (user == null) {
                    throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "用户信息缺失");
                }
                commentUsers.add(user);
            }

            // 获取帖子作者信息
            User postAuthor = userService.getUserById(post.getUserId());
            postAuthor.setEmail("***");
            postAuthor.setPassword("***");
            // 处理用户点赞状态
            Integer userId = (Integer) request.getSession().getAttribute("userId");
            if (userId != null) {
                for (Comments comment : comments) {
                    int isLiked = commentsService.isLikedByUser(userId, comment.getId());
                    comment.setIsLiked(isLiked);
                }
            }

            // 构建响应数据

            response.put("userId", userId);
            response.put("post", post);
            response.put("comments", comments);
            response.put("commentsCount", commentsPageInfo.getTotal());
            response.put("postAuthor", postAuthor);
            response.put("commentUsers", commentUsers);
            response.put("pageNum", pageNum);
            response.put("pageSize", pageSize);
            response.put("totalPages", commentsPageInfo.getPages());
            response.put("hasNextPage", commentsPageInfo.isHasNextPage());

            return ResponseEntity.ok(response);

        } catch (BusinessException e) {
            Map<String, Object> error = new HashMap<>();
            error.put("code", e.getErrorCode());
            error.put("message", e.getErrorMessage());
            return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> error = new HashMap<>();
            error.put("code", Code.SYSTEM_DB_ERROR);
            error.put("message", "获取评论失败");
            return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    @ApiOperation(value = "评论的方法")
    @PostMapping("/posts/comment")
    @ResponseBody // 添加该注解,表示Spring应返回JSON数据
    public ResponseEntity<Map<String, Object>> comment(
            @RequestParam String content,
            @RequestParam int postId,
            HttpServletRequest request) {

        Map<String, Object> response = new HashMap<>();
        try {
            // 参数校验
            if (content == null || content.trim().isEmpty()) {
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "评论内容不能为空");
            }

            // 权限校验
            User user = (User) request.getSession().getAttribute("user");
            if (user == null) {
                throw new BusinessException(Code.PROJECT_ACCESS_DENIED, "用户未登录");
            }

            // 帖子校验
            Posts post = postsService.selectById(postId);
            if (post == null) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "帖子不存在");
            }

            // 创建评论
            Comments comments = new Comments();
            comments.setContent(content);
            comments.setUserId(user.getId());
            comments.setPostId(postId);
            //添加评论信息
            System.out.println("user::"+user.getId());
            Integer id = user.getId();
            String result = postsService.comment(comments,id);


            //获取该帖子所有评论
            List<Comments> commentList = postsService.getCommentsByPostId(postId);
            //获取所有帖子的用户
            List<User> userList = new ArrayList<>();
            for(Comments comments1 : commentList){
                User userById = userService.getUserById(comments1.getUserId());
                user.setEmail("***");
                user.setPassword("***");
                userList.add(userById);
            }

            // 构建成功响应
            response.put("success", true);
            response.put("data", result);
            response.put("commentList", commentList);
            response.put("user", user);
            response.put("userList", userList);
            return ResponseEntity.ok(response);

        } catch (BusinessException e) {
            // 业务异常处理
            e.printStackTrace();
            response.put("success", false);
            response.put("errorCode", e.getErrorCode());
            response.put("errorMessage", e.getErrorMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        } catch (Exception e) {
            // 系统异常处理
            e.printStackTrace();
            response.put("success", false);
            response.put("errorCode", Code.SYSTEM_DB_ERROR);
            response.put("errorMessage", "发表评论失败");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    // 浏览
    @ApiOperation(value = "浏览的方法")
    @PostMapping("/posts/view")
    public ModelAndView view(@RequestParam int postId) {
        ModelAndView mav = new ModelAndView();
        try {
            postsService.view(postId);
            mav.addObject("result", "浏览成功");
            return mav;
        } catch (Exception e) {
            // 捕获异常并抛出 BusinessException
            throw new BusinessException(Code.SYSTEM_UNKNOWN_ERROR, "浏览时发生未知错误");
        }
    }

    // 转发
    @ApiOperation(value = "转发的方法")
    @PostMapping("/posts/share")
    public ModelAndView share(@RequestParam int postId) {
        ModelAndView mav = new ModelAndView();
        try {
            postsService.share(postId);
            mav.addObject("result", "转发成功");
            return mav;
        } catch (Exception e) {
            // 捕获异常并抛出 BusinessException
            throw new BusinessException(Code.SYSTEM_UNKNOWN_ERROR, "转发时发生未知错误");
        }
    }

    @ApiOperation(value = "删除的评论的方法")
    @ResponseBody
    @PostMapping("/posts/comment/user")
    public Map<String, Object> deleteCommentByUser(@RequestParam int commentId, HttpServletRequest request) {
        try {
            // 权限校验
            Object userIdObj = request.getSession().getAttribute("userId");
            if (userIdObj == null) {
                throw new BusinessException(Code.PROJECT_ACCESS_DENIED, "用户未登录，请先登录");
            }
            int userId = (int) userIdObj;

            // 检查评论是否存在且属于当前用户
            Comments comment = postsService.getCommentById(commentId);
            int postId = comment.getPostId();
            if (comment == null) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "评论不存在或已被删除");
            }
            // 检查当前用户是否是帖子作者
            Posts post = postsService.selectById(comment.getPostId());
            if (comment.getUserId() == userId||post.getUserId() == userId) {
                // 执行删除操作
                String result = postsService.deleteCommentByUser(commentId, userId);

                // 查询删除后的评论列表
                List<Comments> commentsList = postsService.getCommentsByPostId(postId);

                // 构建返回的JSON数据
                Map<String, Object> response = new HashMap<>();
                response.put("result", result);
                response.put("commentsList", commentsList);

                return response;
            }
            else{
                throw new BusinessException(Code.PROJECT_ACCESS_DENIED, "无权删除他人评论");
            }
        } catch (BusinessException e) {
            throw e; // 业务异常直接抛出
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "删除评论操作失败", e);
        }
    }


    // 在首页根据关键字查询帖子，视频，用户
    @ApiOperation(value = "在首页根据关键字查询帖子，视频，用户的方法")
    @GetMapping("/selectByKeywords")
    public ModelAndView selectByKeywords(@RequestParam String keywords, HttpServletRequest request) {
        try {
            if (keywords == null || keywords.trim().isEmpty()) {
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "搜索关键词不能为空");
            }
            User u = (User)request.getSession().getAttribute("user");
            ModelAndView mav = new ModelAndView("searchResult");

            // 查询帖子
            List<Posts> posts = postsService.selectByKeywords(keywords);
            if (posts != null && !posts.isEmpty()) {
                List<User> postUsers = new ArrayList<>();
                for (Posts post : posts) {
                    //判断点赞状态
                    int isLiked = postsService.isLike(post.getId(), u.getId());
                    post.setIsLiked(isLiked);

                    User user = userService.getUserById(post.getUserId());
                    if (user != null) {
                        user.setEmail("***");
                        user.setPassword("***");
                        postUsers.add(user);
                    }
                }
                mav.addObject("users", postUsers)
                        .addObject("posts", posts);
            }

            // 查询用户
            List<User> users = userService.selectByKeywords(keywords);
            for(User user1:users){
                boolean isFollowing = followersService.isFollowing(u.getId(), user1.getId());
                user1.setFollowing(isFollowing);
            }
            if (users != null && !users.isEmpty()) {
                mav.addObject("users1", users);
            }

            // 查询视频
            List<Videos> videos = videosService.selectByKeywords(keywords);
            if (videos != null && !videos.isEmpty()) {
                List<User> videoUsers = new ArrayList<>();
                for (Videos video : videos) {
                    User user = userService.getUserById(video.getUserId());
                    user.setEmail("***");
                    user.setPassword("***");
                    if (user != null) {
                        videoUsers.add(user);
                    }
                }
                mav.addObject("users2", videoUsers)
                        .addObject("videos", videos);
            }

            // 如果所有结果都为空
            if ((posts == null || posts.isEmpty()) &&
                    (users == null || users.isEmpty()) &&
                    (videos == null || videos.isEmpty())) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "未找到相关内容");
            }

            // 判断用户角色，决定返回的视图
            User currentUser = (User) request.getSession().getAttribute("user");
            String viewName = "searchResult";
            if (currentUser != null && "admin".equals(currentUser.getRole())) {
                viewName += "Manager";
            }
            mav.setViewName("searchResult");

            mav.addObject("keywords", keywords);
            return mav;
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "搜索失败", e);
        }
    }

    //热搜实现
    @ApiOperation(value="获取热搜的方法")
    @GetMapping("/mainPageTrending")
    public ModelAndView hotPosts(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();

        try {
            // 检查用户登录状态
            User u = (User) request.getSession().getAttribute("user");
            // 生成热搜排行序号
            int[] nums = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
                    16,17,18,19,20};

            // 获取热搜数据
            List<Posts> hotPosts = postsService.hotPosts();
            if (hotPosts == null || hotPosts.isEmpty()) {
                throw new BusinessException(
                        Code.PROJECT_DATA_NOT_FOUND,
                        "暂无热搜数据"
                );
            }

            // 判断用户角色，决定返回的视图
            String viewName = "mainPageTrending";
            if (u != null && "admin".equals(u.getRole())) {
                viewName += "Manager";
            }

            // 设置视图数据
            mav.addObject("nums", nums);
            mav.addObject("user", u);
            mav.addObject("posts", hotPosts);
            mav.setViewName(viewName);

        } catch (BusinessException e) {
            // 业务异常直接抛出
            throw e;
        } catch (Exception e) {
            // 系统异常包装后抛出
            throw new SystemException(
                    Code.SYSTEM_DB_ERROR,
                    "获取热搜数据失败",
                    e
            );
        }

        return mav;
    }
}